<?php
/**
 * 产品类别逻辑类
 * @author zengnz
 *
 */
class ProductCategoryLogic extends CommonModel
{
	const USER_PRODUCT_CATEGORY = 'USER_PRODUCT_CATEGORY_';
	
	// 缓存模型类
	private $_CacheModel = '';
	
	public function __construct() {
		$this -> _CacheModel = D('Cache', 'Service');
		$this -> _CacheModel -> init();
	
	}

	/**
	 * 根据用户ID获取产品类别
	 * @param integer $uId 
	 * @param integer $shopId
	 * @return array or -1参数错误
	 */
	public function getProductCategory( $uId, $shopId ) {
		if (!$uId)
			return -1;
		
		$key = self::USER_PRODUCT_CATEGORY.$uId.'_'.$shopId;
		
		$category = $this -> _CacheModel -> get($key);
		if (!$category) {
			$sql = 'shop_id='.$shopId.' AND customer_id='.$uId;
			$Model = D('ProductCategory');
			$category = $Model -> field('*') 
					-> where($sql)
					-> select();
			
			$this -> _CacheModel -> set($key, $category);
			$this -> _CacheModel -> saveKeys($key, 'user', $uId);
		}
		
		return $category;
	}
	
	/**
	 * 判断类别名称是否已经存在
	 * @param integer $uId
	 * @param integer $shopId
	 * @param string $name
	 * @return true 存在 false 不存在
	 */
	public function productCategoryNameExists( $uId, $shopId, $name ) {
		$category = $this -> getProductCategory($uId, $shopId);
		foreach ($category as $val) {
			if ($val['name'] == trim($name))
				return true;
		}
		
		return false;
	}
	
	
	/**
	 * 添加产品类型
	 * @param integer $uId
	 * @param integer $shopId
	 * @param array $info
	 * @return -1 参数错误  false添加失败
	 */
	public function addProductCategory($shopId, $pid, $name) {
		if (!$shopId) 
			return -1;
	
		$uId = $this -> getUid();
		$key = self::USER_PRODUCT_CATEGORY.$uId.'_'.$shopId;
		
		$Model = D('ProductCategory');
		$info = array(
			'pid' => $pid,
			'name' => $name,
			'shop_id' => $shopId,
			'customer_id' => $uId,
		);
		
		$ret = $Model -> add($info);
		
		if ($ret)
			$this -> _CacheModel -> rm($key);
		
		return $ret;
	}
	
	
}